package yygh.order.Service.imp;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import yygh.hospital.enums.OrderStatusEnum;
import yygh.hospital.model.order.OrderInfo;
import yygh.hospital.model.user.Patient;
import yygh.hospital.vo.hosp.ScheduleOrderVo;
import yygh.hospital.vo.msm.MsmVo;
import yygh.hospital.vo.order.*;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import yygh.common.execption.HospitalException;
import yygh.common.helper.HttpRequestHelper;
import yygh.common.result.ResultCodeEnum;
import yygh.hosp.client.HospFeignClient;
import yygh.order.Mapper.OrderMapper;
import yygh.order.Service.OrderService;
import yygh.order.Service.WeixinService;
import yygh.rabbitmq.Service.RabbitService;
import yygh.rabbitmq.constant.MqConst;
import yygh.user.client.PatientFeignClient;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderServiceImp extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {


    @Autowired
    PatientFeignClient patientFeignClient;

    @Autowired
    HospFeignClient hospFeignClient;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    RabbitService rabbitService;

    @Autowired
    WeixinService weixinService;


    //Service层，生成预约挂号订单
    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        //远程调用获取就诊人的信息
        Patient patient = patientFeignClient.getPatientOrder(patientId);
        //远程调用，获取排班相关信息
        ScheduleOrderVo scheduleOrderVo = hospFeignClient.getScheduleOrderVo(scheduleId);
        //判断当前时间是否还可以预约
        if (new DateTime(scheduleOrderVo.getStartTime()).isAfterNow() || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
            throw new HospitalException(ResultCodeEnum.TIME_NO);
        }
        //添加到订单表, scheduleOrderVo 数据复制到 orderInfo
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
        //向orderInfo中设置其他数据
        String outTradeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setScheduleId(scheduleId);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        //更新orderInfo到数据库
        baseMapper.insert(orderInfo);

        //调用医院系统接口hospital_mangaer,完成预约挂号操作
        //调用医院系统接口需要传入参数，这些参数统一封装在map集合中
        //获取签名信息
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode", orderInfo.getHoscode());
        paramMap.put("depcode", orderInfo.getDepcode());
        paramMap.put("hosScheduleId", orderInfo.getScheduleId());
        paramMap.put("reserveDate", new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount", orderInfo.getAmount());

        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType", patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex", patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone", patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode", patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode", patient.getDistrictCode());
        paramMap.put("address", patient.getAddress());
        //联系人
        paramMap.put("contactsName", patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo", patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone", patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());

        String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", sign);
        //调用医院系统接口,传入封装的paramMap和url路径地址
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");

        //调用后进行相关参数的封装
        if (result.getInteger("code") == 200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");
            ;
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");
            ;
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");
            ;
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");

            //下单成功后可以使用rabbitmq消息中间件进行号源的更新和短信通知。
            //通过mq实现排班可预约数和排班剩余预约数的更新
            OrderMqVo orderMqVo=new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setAvailableNumber(availableNumber);
            orderMqVo.setReservedNumber(reservedNumber);

            //设置短信提醒
            MsmVo msmVo=new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午" : "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);
            //调用mq发送短信的方法
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);
        }else {
            throw  new HospitalException(result.getString("message"),ResultCodeEnum.FAIL.getCode());
        }

        return orderInfo.getId();

    }

    /**
     * 订单相关接口
     * @param orderId
     * @return
     */

    //Service层，根据订单编号查找订单详情
    @Override
    public OrderInfo getOrder(String orderId) {
        OrderInfo orderInfo = orderMapper.selectById(orderId);
        this.packOrderInfo(orderInfo);
        return  orderInfo;
    }

    //Service层实现订单列表的展示（参考用户列表的展示）
    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> page, OrderQueryVo orderQueryVo) {
        //根据查询条件userInfoQueryVo获取条件值
        String name = orderQueryVo.getKeyword(); //用户名称
        Long patientId = orderQueryVo.getPatientId();//就诊人名称
        String orderStatus = orderQueryVo.getOrderStatus();//订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();//订单创建的时间
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();//

        //根据条件值是否为空进行相关的封装
        //对条件值进行非空判断
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            queryWrapper.like("hosname",name);
        }
        if(!StringUtils.isEmpty(patientId)) {
            queryWrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)) {
            queryWrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(reserveDate)) {
            queryWrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            queryWrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            queryWrapper.le("create_time",createTimeEnd);
        }
        //进行条件分页查询。
        IPage<OrderInfo> orderInfoPage = orderMapper.selectPage(page, queryWrapper);

        //封装对应的值，将其状态status的具体中文解释展现，如1-锁定，0-正常
        orderInfoPage.getRecords().stream().forEach(item->{
            this.packOrderInfo(item);
        });
        return  orderInfoPage;
    }

    @Override
    public Boolean cancelOrder(String orderId) {
        //根据orderId获取订单信息；
        OrderInfo orderInfo = orderMapper.selectById(orderId);
        //获取订单的退款时间
        Date quitTime = orderInfo.getQuitTime();
        //判断取消的时间是否超过了规定的时间；
        if (new DateTime(quitTime).isBeforeNow()) {
            //退款时间已过
            throw new HospitalException(ResultCodeEnum.CANCEL_ORDER_FAIL);
        }
        //调用医院接口实现预约取消；
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if (null == signInfoVo) {
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode", orderInfo.getHoscode());
        reqMap.put("hosRecordId", orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);
        //调用医院接口，返回数据
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl() + "/order/updateCancelStatus");

        if (result.getInteger("code").intValue() != 200) {
            //取消预约失败
            throw new HospitalException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }else {

        //取消预约成功，调用微信退款方法，进行微信退款；
        //判断当前订单是否可以取消
        if (orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus()) {
            Boolean refund = weixinService.refund(orderInfo.getId());
            if (!refund) {
                throw new HospitalException(ResultCodeEnum.CANCEL_ORDER_FAIL);
            }
            //微信退款成功，更新订单的状态；
            orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
            orderMapper.updateById(orderInfo);
            //mq发送消息
            //发送mq更新预约数量
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(orderInfo.getScheduleId());
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
        }
    }
            return true;
    }

    /**
     * 就诊消息通知
     */
    @Override
    public void patientTip() {
        //根据要求寻找需要通知的就诊人（根据就诊安排时间和订单状态）
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        //不通知订单状态为-1的已经取消的就诊人
        queryWrapper.ne("order_status",OrderStatusEnum.CANCLE.getStatus());
        List<OrderInfo> orderInfoList = orderMapper.selectList(queryWrapper);
        //进行逐一通知
        for (OrderInfo orderInfo:orderInfoList){
            //进行短信通知
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(orderInfo.getScheduleId());
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
        }
    }

    /**
     * 内部接口方法实现类：获取订单统计数据
     * @param orderCountQueryVo
     * @return
     */
    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        //根据mapper.xml获取预约订单数量
        List<OrderCountVo> orderCountVos = orderMapper.selectOrderCount(orderCountQueryVo);
        //遍历集合，获取x需要数据 ，日期数据  list集合
        List<String> dateList = orderCountVos.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        // //获取y需要数据，具体数量  list集合
        List<Integer> countLit = orderCountVos.stream().map(OrderCountVo::getCount).collect(Collectors.toList());

        //封装需要返回的数据
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("dateList",dateList);
        resultMap.put("countLit",countLit);

        return  resultMap;
    }


    //封装OrderInfo信息，将其"订单状态"封装成具体的中文
    private void packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString",OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
    }

}
